﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

using WXDba.Entity;
using WXDba.Abstract;
using System.Data.Entity;
using System.Xml;

namespace WXPackage
{
    /// <summary>
    /// 发送消息管理
    /// </summary>
    public class SendMessage : BaseManage
    {
        IMsgRecord _IMsgRecord = ConcreteFactory.GetMsgRecord();
        /// <summary>
        /// 接受者
        /// </summary>
        public string ToUserName { get; set; }
        /// <summary>
        /// 发送者消息
        /// </summary>
        public string FromUserName { get; set; }
        /// <summary>
        /// 针对回复的消息
        /// </summary>
        private MsgRecord _msg { get; set; }
        /// <summary>
        /// 当前请求响应对象
        /// </summary>
        private HttpResponse resp = null;
        /// <summary>
        /// 初始化对象
        /// </summary>
        /// <param name="ToUserName">接受者</param>
        /// <param name="FromUserName">发送者</param>
        public SendMessage(string ToUserName, string FromUserName)
        {
            this.ToUserName = ToUserName;
            this.FromUserName = FromUserName;
            _msg = new MsgRecord()
            {
                ToUserName = ToUserName,
                FromUserName = FromUserName,
                CreateTime = DateTime.Now
            };
            resp = HttpContext.Current.Response;
        }
        public SendMessage(MsgRecord record)
        {
            _msg = new MsgRecord()
            {
                ToUserName = record.FromUserName,
                FromUserName = record.ToUserName,
                CreateTime = DateTime.Now
            };
            resp = HttpContext.Current.Response;
        }
        /// <summary>
        /// 发送文本消息
        /// </summary>
        /// <param name="content"></param>
        public void SendText(string content)
        {
            if (string.IsNullOrEmpty(content))
                throw new Exception("发送消息内容不能为空");
            _msg.CreateTime = DateTime.Now;
            _msg.MsgType = "text";
            try
            {
                string result = WriteContent(content);
                LogOperate.Write("响应内容-----》" + result);
                _msg.Content = content;
                //保存发送信息
                _msg.AddTime = DateTime.Now;
                _IMsgRecord.Add(_msg);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("发送text内容失败，当前content={0},错误描述：{1}",
                    content,
                    ex.Message));
            }
        }
        /// <summary>
        /// 指定content，获取相应xml字符串
        /// </summary>
        /// <param name="content">文字内容</param>
        /// <returns></returns>
        private string WriteContent(string content)
        {
            XmlDocument doc = new XmlDocument();
            XmlElement xml = doc.CreateElement("xml");
            xml.AppendChild(getElem(doc, "ToUserName", _msg.ToUserName));
            xml.AppendChild(getElem(doc, "FromUserName", _msg.FromUserName));
            long curTime = (long)(DateTime.Now - new DateTime(1970, 1, 1)).TotalSeconds;
            xml.AppendChild(getElem(doc, "CreateTime", curTime.ToString()));
            xml.AppendChild(getElem(doc, "MsgType", _msg.MsgType));
            //根据消息类型，发送不同内容
            if (_msg.MsgType == "text")
            {
                xml.AppendChild(getElem(doc, "Content", content));
            }
            if (resp == null)
                throw new Exception("响应消息内容时，获取相应对象resp失败");
            resp.Clear();
            resp.ContentType = "text/xml";
            resp.ContentEncoding = Encoding.UTF8;
            ////将xml文档输出响应流
            //using (XmlWriter xw = XmlWriter.Create(resp.Output))
            //{
            //    xml.WriteTo(xw);
            //    xw.Flush();
            //}

            //将xml文档输出响应流，方法2
            StringBuilder builder = new StringBuilder();
            using (XmlWriter xw = XmlWriter.Create(builder))
            {
                xml.WriteTo(xw);
                xw.Flush();
            }
            resp.Write(builder.ToString());
            resp.End();

            return builder.ToString();
        }
        /// <summary>
        /// 创建节点
        /// </summary>
        private XmlElement getElem(XmlDocument doc, string key, string value)
        {
            XmlElement elem = doc.CreateElement(key);
            elem.InnerText = value;
            return elem;
        }
    }
}
